#! /usr/bin/python
# -*- coding: UTF-8 -*-
# 添加OC垃圾代码
import os,sys
import random
import string
import re
import md5
import time
import json
import shutil
import hashlib 
import time
import argparse
import codecs
from biplist import *

import sys 
reload(sys) 
sys.setdefaultencoding("utf-8")

script_path = os.path.split(os.path.realpath(sys.argv[0]))[0]
#垃圾代码临时存放目录
target_ios_folder = os.path.join(script_path, "./target_ios")

#生成垃圾文件个数
total_class_num = 60

#方法列表，用以随机方法
with open(os.path.join(script_path, "./Class_list.json"), "r") as fileObj:
    Class_name_list = json.load(fileObj)

#单词列表，用以随机名称
with open(os.path.join(script_path, "./insertAPIName.plist"), "r") as fileObj:
    insertAPI_name_list = readPlist(fileObj)

#获取随机字符串
def generate_array_className(number):
    global Class_name_list
    return Class_name_list[number]

#获取随机字符串
def generate_random_ClassName():
    global Class_name_list
    return random.choice(Class_name_list)

#获取一个类名
def getClassName(number):
    return generate_array_className(number) + 'ViewController'

#oc代码头文件函数声明
def getOCHeaderFuncText(number):
    funcName = 'pushTo' + generate_array_className(number) + 'VC'
    text = "\n- (void)%s" %(funcName)
    return text

#oc代码函数实现模板
def getOCFuncText(header_text):
    global insertAPI_name_list
    arg1 = random.choice(insertAPI_name_list)
    text = [
        header_text + "\n",
        "{\n",
        "\t %s  \n" %(arg1),
        "}\n"
    ]
    return "".join(text)

#oc代码以@end结尾，在其前面添加text
def appendTextToOCFile(file_path, text):
    with open(file_path, "r") as fileObj:
        old_text = fileObj.read()
        fileObj.close()
        end_mark_index = old_text.rfind("@end")
        if end_mark_index == -1:
            print "\t非法的结尾格式: " + file_path
            return
        new_text = old_text[:end_mark_index]
        new_text = new_text + text + "\n"
        new_text = new_text + old_text[end_mark_index:]

    with open(file_path, "w") as fileObj:
        fileObj.write(new_text)

#处理单个OC文件，添加垃圾函数。确保其对应头文件存在于相同目录
def dealWithOCFile(filename, file_path):

    end_index = file_path.rfind(".")
    pre_name = file_path[:end_index]
    header_path = pre_name + ".h"
    if not os.path.exists(header_path):
        print "\t相应头文件不存在：" + file_path
        return

    global Class_name_list
    new_func_num = len(Class_name_list)
    
    for i in range(new_func_num):
        header_text = getOCHeaderFuncText(i)
        result = filename.split('ViewController.m')[0] in header_text
        if result == True:
            print  '此时包含'
        else:
            appendTextToOCFile(header_path, header_text + ";\n")
            funcText = getOCFuncText(header_text)
            appendTextToOCFile(file_path, funcText)

#扫描parent_folder，添加垃圾函数，处理了忽略列表
def addOCFunctions(parent_folder):

    for parent, folders, files in os.walk(parent_folder):
        need_ignore = None
        if need_ignore:
            print "\t忽略文件夹" + ignore_folder
            continue

        for file in files:
            if file.endswith(".m") or file.endswith(".mm"):
                dealWithOCFile(file, os.path.join(parent, file))

#新创建的垃圾文件header模板
def getOCHeaderFileText(class_name):

    propertyStr = ''

    for header_text in Class_name_list:
        
        result = class_name.split('ViewController')[0] in header_text

        if result == True:
            print  '此时包含'
        else:
          propertyStr += "@property (strong,nonatomic)NSString * %s; \n" %(header_text)

    text = [
        "//  UnityAppController.h \n",
        "//  KXNewVersionCheck \n",
        "//  Created by Apple. \n",
        "//  Copyright © 2018年 All rights reserved. \n\n",
        "#import <Foundation/Foundation.h> \n",
        "#import <UIKit/UIKit.h> \n\n",
        "#import \"UnityAppController.h\" \n\n",
        "@interface %s : UnityAppController \n" %(class_name),
        "%s" %(propertyStr),
        "\n\n@end"
    ]
    return string.join(text)


#新创建的垃圾文件mm模板
def getOCMMFileText(class_name):
    text = [
        "//  UnityAppController.m\n",
        "//  KXNewVersionCheck\n",
        "//  Created by Apple.\n",
        "//  Copyright © 2018年 All rights reserved.\n\n",
        '#import "%s.h"\n\n' %(class_name),
        '@interface %s()\n' %(class_name),
        "\n@end\n\n"
        "@implementation %s\n" %(class_name),
        "\n\n@end"
    ]
    return string.join(text)

#添加垃圾文件到parent_folder/trash/
def addOCFile(parent_folder):
    
    file_list = []
    target_folder = os.path.join(parent_folder, "trash")
    if os.path.exists(target_folder):
        shutil.rmtree(target_folder)
    os.mkdir(target_folder)

    global Class_name_list
    file_num = len(Class_name_list)
    for i in range(file_num):
        file_name = getClassName(i)
        file_list.append("#import \"" + file_name + ".h\"")
       
        header_text = getOCHeaderFileText(file_name)
        full_path = os.path.join(target_folder, file_name + ".h")
        with open(full_path, "w") as fileObj:
            fileObj.write(header_text)
            fileObj.close()

        mm_text = getOCMMFileText(file_name)
        full_path = os.path.join(target_folder, file_name + ".m")
        with open(full_path, "w") as fileObj:
            fileObj.write(mm_text)
    all_header_text = "\n".join(file_list)

    with open(os.path.join(parent_folder, "Trash.h"), "w") as fileObj:
        fileObj.write(all_header_text)
        fileObj.close()

#解析参数       
def parse_args():
    parser = argparse.ArgumentParser(description='oc垃圾代码生成工具.')
    parser.add_argument('--oc_folder', dest='oc_folder', type=str, required=True, help='OC代码所在目录')
    parser.add_argument('--replace', dest='replace_ios', required=False, help='直接替换oc源代码', action="store_true")

    args = parser.parse_args()
    return args


#生成一个指定长度的随机字符串
def generate_random_str():
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz'
    length = len(base_str) - 1
    for i in range(8):
        random_str += base_str[random.randint(0, length)]
    return random_str



#清空类名、重新生成新的
def modify_Class_name():
    
    with open("./Class_list.json", "r+") as f:
        read_data = f.read()
        f.seek(0)
        f.truncate()   #清空文件

    global total_class_num

    class_name_arr = []

    for index in range(total_class_num):

        random_str_class = generate_random_str()
        class_name_arr.append(random_str_class)

    with open("./Class_list.json", "w") as f:
        json.dump(class_name_arr,f)
        f.closed



def main():
    
    app_args = parse_args()
    
    if os.path.exists(target_ios_folder):
        shutil.rmtree(target_ios_folder)

    modify_Class_name()

#    创建文件夹
    os.makedirs(target_ios_folder)

    print "开始创建oc文件到trash目录"
    addOCFile(target_ios_folder)
    print "\n开始添加oc方法"
    addOCFunctions(target_ios_folder)


    print "垃圾代码生成完毕，垃圾代码目录：" + os.path.abspath(target_ios_folder)

    print "\nfinished"

if __name__ == "__main__":
    main()
